from QQLoginTool.QQtool import OAuthQQ

from django.conf import settings
from django.shortcuts import render
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings


from oauth.models import OAuthQQUser
from oauth.serializers import QQUserSerializer
from oauth.utils import generate_encrypted_openid


class QQURLView(APIView):

    def get(self, request):
        # 获取请求参数: next
        next = request.query_params.get('next')
        if not next:
            next = '/index.html'

        # 通过第三方包QQLoginTool: 生成QQ登录界面的url地址
        oauthqq = OAuthQQ(settings.QQ_CLIENT_ID,
                          settings.QQ_CLIENT_SECRET,
                          settings.QQ_REDIRECT_URI,
                          state=next)

        login_url = oauthqq.get_qq_url()

        # 返回QQ登录界面的url地址
        return Response({'login_url': login_url})


class QQUserView(APIView):

    def get(self, request):
        # 提取code请求参数
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'},
                            status=status.HTTP_400_BAD_REQUEST)
        # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)

        except:
            return Response({'message': 'QQ服务异常'},
                            status=status.HTTP_503_SERVICE_UNAVAILABLE)

        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:

            openid = generate_encrypted_openid(openid)

            return Response({'openid': openid})
        else:

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            user = oauth_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response

    def post(self, request):

        serializer = QQUserSerializer(data=request.data)

        serializer.is_valid(raise_exception=True)

        user = serializer.save()  # 返回绑定的美多用户对象

        # todo: 生成jwt
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        context = {
            'token': token,
            'user_id': user.id,
            'username': user.username
        }
        return Response(context)










